<?php
/**
 * Created by PhpStorm.
 * User: 69548
 * Date: 2018/9/21
 * Time: 9:56
 */

namespace app\wap\controller;

use think\Controller;
use think\Cookie;
use think\Request;
use app\api\controller\Trip as TripApi;

class Trip extends Basewap
{
    public function index(){
        $post=request()->request();
        $da=db('trip')
            ->where('id',$post['trip_id'])
            ->field('adminid,id as trip_id,price,priceno,name,description,
            introduction,days,people,back,careful,section_json,start_go_time,
            showback,showcareful,showprice,showintroduction,thumb_map_img,thumb_map_name,
            budget_price,trip_banner,show_day_map,show_city_map,showpricedetail,
            total_price,insurancePrice,insuranceDetail,
            totalHotelPrice,totalDrivePrice,totalTicketPrice,
            totalExtraPrice,totalTransPrice,totalAirportPrice,
            totalAirportPrice_rate,totalHotelPrice_rate,
            totalDrivePrice_rate,totalTransPrice_rate,
            totalTicketPrice_rate,insurancePrice_rate,
            totalExtraPrice_rate,total_sale_price,isPaid,isConfirm,admin_confirm,custom_made_description')
            ->find();
        $name=db('admin')->where('id',$da['adminid'])->field('nickname,wx_qrcode')->find();
        $da['admin_name']=$name['nickname'];
        //如果未上传微信二维码 则使用小美的微信二维码 12363
        $name['wx_qrcode'] = !empty($name['wx_qrcode'])?$name['wx_qrcode']:12363;
        $da['wx_qrcode'] = geturl($name['wx_qrcode'])??"";
        $da['isDrive'] = false;
        if ($da['showback']==0){
            $da['back']='';
        }
        if ($da['showcareful']==0){
            $da['careful']='';
        }
        if ($da['showprice']==0){
            $da['price']='';
            $da['priceno']='';
        }
        if ($da['showintroduction']==0){
            $da['introduction']='';
        }
        if (empty($da)) return json_encode(['msg'=>'没有找到行程请联系客服人员','code'=>101]);
        $rc= db('schedule')
            ->where('groupid',$post['trip_id'])
            ->order('displayorder asc')
            ->field('id,time,title,transport_typeids,day_description,thumb_map_img,thumb_map_name')
            ->select();
        if (empty($rc)) json_encode(['msg'=>'没有日程安排','code'=>101]);
        if (count($rc)>1){
            $end= end($rc);
        }else{
            $end= $rc[0];
        }
        $top=$rc[0];
        $da['time']='--';
        if (!empty($top['time'])&&!empty($end['time'])){
            $da['time']= $top['time'].'--'.$end['time'];
        }
        if (empty($end['time'])){
            $da['time']= $top['time'];
        }

        $city_id=[];
        $da['city_name']='';
        $keyArr = array();//索引集合
        //开始遍历日程
        $allcityIds = $allcitys = $allcityLatLngs = [];
        $activeTypeList = (new TripApi())->getGlobalActiveTypeList(false);
        $includePoiActiveTypeList = (new TripApi())->getGlobalActiveTypeList();
        //判断是否拥有 美食等附加信息
        $hasExtra = false;
        foreach ($rc as $k=>$v){
            //判断是否存在自驾
            if(!empty($v['transport_typeids'])){
                $transport_typeid = explode(",",$v['transport_typeids']);
                if(in_array(7,$transport_typeid)){
                    $da['isDrive'] = true;
                }
            }

            $xq=db('active a')
                ->join("city c","c.id=a.cityid",'left')
                ->join("poi p","p.id=a.poiid",'left')
                ->field("a.*,c.lat as c_lat,c.lng as c_lng,c.eng_name as cityEngName,
                p.introduce as p_introduce,p.lat,p.lng,p.thumb as poi_thumb,p.eng_introduce,
                p.open_time,p.ticket,p.price,p.grade,p.description,p.thumb,p.source,p.mobile,
                p.ticket_url,p.address")
                ->where('a.groupid',$v['id'])
                ->order('a.displayorder asc')
                ->select();

            $activeKeyArr = [];
            //开始遍历节点
            foreach ($xq as $t=>$y){
                if(in_array($y['activeType'],$activeTypeList)){
                    $hasExtra = true;
                }
                //所有城市经纬度
                $cityLatLng = [
                    'lat'=>floatval($y['c_lat']),
                    'lng'=>floatval($y['c_lng']),
                    'id'=>$y['cityid'],
                    'type'=>'city',
                    'name'=>$y['cityname'],
                    'eng_name'=>$y['cityEngName'],
                ];
                //重复的城市不录入经纬度
                if(!empty($y['cityid']) && !in_array($y['cityid'],$allcityIds)){
                    array_push($allcityIds,$y['cityid']);
                    array_push($allcityLatLngs,$cityLatLng);
                }
                //节点经纬度
                $rc[$k]['hasLine'] = false;
                $vo_start_poi=[];
                $vo_end_poi=[];
                $vo_ways_poi=[];
                $vo_latLng = [];
                if(count($xq)>=2 && $da['show_day_map']==1){
                    $vo_latLng = $xq;
                    foreach ($vo_latLng as $v_key=>$v_poi){
                        //判断开始的类型
                        if(in_array($v_poi['activeType'],[1,4,15])){
                            $vo_latLng[$v_key]['lat'] = $v_poi['lat'];
                            $vo_latLng[$v_key]['lng'] = $v_poi['lng'];
                        }elseif(in_array($v_poi['activeType'],[2,3])){
                            $vo_latLng[$v_key]['lat'] = $v_poi['airport_lat'];
                            $vo_latLng[$v_key]['lng'] = $v_poi['airport_lng'];
                        }else{
                            $vo_latLng[$v_key]['lat'] = "";
                            $vo_latLng[$v_key]['lng'] = "";
                        }

                        if(empty($vo_latLng[$v_key]['lat']) || empty($vo_latLng[$v_key]['lng'])){
                            unset($vo_latLng[$v_key]);
                        }
                    }
                    $vo_start_poi=array_shift($vo_latLng);
                    if(count($vo_latLng)>0){
                        $vo_end_poi=array_pop($vo_latLng);
                    }else{
                        $vo_end_poi=[
                            'lat'=>0,
                            'lng'=>0
                        ];
                    }
                    if(!empty($vo_start_poi['lat']) && !empty($vo_start_poi['lng']) && !empty($vo_end_poi['lat']) && !empty($vo_end_poi['lng'])){
                        $vo_start_poi = [[
                            'lat'=>$vo_start_poi['lat'],
                            'lng'=>$vo_start_poi['lng'],
                            'title'=>$vo_start_poi['poiname'],
                            'id'=>$vo_start_poi['id'],
                        ]];
                        $vo_end_poi = [[
                            'lat'=>$vo_end_poi['lat'],
                            'lng'=>$vo_end_poi['lng'],
                            'title'=>$vo_end_poi['poiname'],
                            'id'=>$vo_end_poi['id'],
                        ]];
                        $rc[$k]['hasLine'] = true;
                    }else{
                        $rc[$k]['hasLine'] = false;
                    }
                    foreach ($vo_latLng as $v_poi){
                        if(isset($v_poi['lat']) && isset($v_poi['lng']) && !empty($v_poi['lat']) && !empty($v_poi['lng'])){
                            $vo_ways_poi[] = ['lat'=>$v_poi['lat'],'lng'=>$v_poi['lng'],'title'=>$v_poi['title'],'id'=>$v_poi['id']];
                        }
                    }
                }
                $rc[$k]['start_poi'] = $vo_start_poi;
                $rc[$k]['end_poi'] = $vo_end_poi;
                $rc[$k]['ways_poi'] = $vo_ways_poi;

                if(!empty($y['cityname'])){
                    $city_id[$y['cityid']]=$y['cityname'];
                }
                $xq[$t]['thumb']='';
                $xq[$t]['address']='';
                $xq[$t]['lat']='';
                $xq[$t]['lng']='';
                $xq[$t]['show']=0;
                if($y['showticket']==0){
                    $xq[$t]['ticket']='';
                }
                if($y['showopen_time']==0){
                    $xq[$t]['open_time']='';
                }
                if($y['showticket_url']==0){
                    $xq[$t]['ticket_url']='';
                }
                if($y['showeng_introduce']==0){
                    $xq[$t]['eng_introduce']='';
                }
                if($y['showdescription']==0){
                    $xq[$t]['description']='';
                }
                if($y['showthumb']==0){
                    $xq[$t]['thumb']='';
                }
                if($y['showsource']==0){
                    $xq[$t]['source']='';
                }
                if($y['showaddress']==0){
                    $xq[$t]['address']='';
                }
                if($y['showgrade']==0){
                    $xq[$t]['grade']='';
                }
                if($y['showmobile']==0){
                    $da['mobile']='';
                }
                if($y['typeid']==2){
                    $xq[$t]['title']=$y['cityname'];
                }

                $xq[$t]['title']=$y['poiname'];

                if(in_array($y['activeType'],$includePoiActiveTypeList)){//   1POI    4酒店
                    if (!empty($y['poiid'])){
                        $poi=  db('poi')->alias('a')
                            ->where('a.id',$y['poiid'])
                            ->join('city c','c.id=a.groupid')
                            ->field('a.*,c.name as city_name')
                            ->find();
                        //若节点不存在 则跳过
                        if(empty($poi)) continue;

                        $xq[$t]['poi_content'] = !empty($y['poi_content'])?$y['poi_content']:$poi['introduce'];
                        if(!empty($y['poiImg'])){
                            $poiImgArr = explode(",",$y['poiImg']);
                            $images = !empty($poiImgArr) ? $poiImgArr : '';
                        }else{
                            $images=!empty($poi['thumb'])?explode(',',$poi['thumb']):'';
                        }

                        if ($images!=''){
                            $gg= array_filter($images);
                            $poi['thumb']=array_values($gg);
                        }else{
                            $poi['thumb']= '';
                        }

                        $da['mobile']=$poi['mobile'];
                        $xq[$t]['title']=$poi['name'];
                        $xq[$t]['eng_name']=$poi['eng_name'];
                        $xq[$t]['thumb']=$poi['thumb'];
                        $xq[$t]['address']=$poi['address'];
                        $xq[$t]['ticket']=$poi['ticket'];
                        $xq[$t]['open_time']=$poi['open_time'];
                        $xq[$t]['ticket_url']=$poi['ticket_url'];
                        $xq[$t]['eng_introduce']=$poi['eng_introduce'];
                        $xq[$t]['description']=$poi['description'];
                        $xq[$t]['grade']=$poi['grade'];
                        $xq[$t]['source']=$poi['source'];
                        $xq[$t]['lat']=$poi['lat'];
                        $xq[$t]['lng']=$poi['lng'];
                        $xq[$t]['show']=0;
                    }else{
                        $xq[$t]['poiid']='';
                        $xq[$t]['eng_name']='';

                        //增加【其它】中图片显示
                        $images=!empty($y['other_images'])?explode(',',$y['other_images']):'';
                        if ($images!=''){
                            $gg= array_filter($images);
                            $image_arr=array_values($gg) ;
                        }else{
                            $image_arr= '';
                        }
                        $xq[$t]['thumb']=$image_arr;
                    }
                }elseif($y['activeType']==2 || $y['activeType']==3 || $y['activeType']==6) {//   2接机    3送机   6其他
                    $xq[$t]['poi_content'] = '';
                    $xq[$t]['poiImg'] = '';
                }

                //索引
                $xq[$t]['name_id'] = "name_".$y['id'];
                if($y['showkey']==1){
                    $typeid = $y['typeid'];
                    if($typeid==3){
                        $keytitle = $y['poiname'];
                    }elseif($typeid==2){
                        $keytitle = $y['cityname'];
                    }else{
                        $keytitle = $y['title'];
                    }

                    $keytitle = $y['poiname'];

                    $activeKeyArr[] = [
                        'id'=>"name_".$y['id'],
                        'title'=>$keytitle,
                    ];
                }
            }
            $rc[$k]['xiangqing']=$xq;
            //索引数组
            $daytitle = $v['title'];
            if($v['title']!==''){
                if(substr($v['title'],0,1)==","){
                    $daytitle = substr($v['title'],1);
                    $rc[$k]['title']=$daytitle;
                }
            }
            $keyArr[] = [
                'day' => "DAY".($k+1)."：",
                'daytitle' => $daytitle,
                'day_key' => "day_".($k+1),
                'active' => $activeKeyArr
            ];
            $rc[$k]['thumb_map_img'] = empty($da['show_day_map'])?"":$v['thumb_map_img'];
            $rc[$k]['thumb_map_name'] = empty($da['show_day_map'])?"":$v['thumb_map_name'];
        }
        //是否有周边
        $da['hasExtra'] = $hasExtra;
        $city_id= array_values($city_id);

        for($i=0;$i<count($city_id);$i++){
            $da['city_name'].=$city_id[$i].',';
        }

        //首图banner
        if(empty($da['trip_banner'])){
            $da['trip_banner'] = 'https://kwibon-public-images.oss-cn-beijing.aliyuncs.com/custom/68fa01cd5691eb3282147a796baf1d98jpg';
        }
        //判断城市地图是否绘制
        //开始城市经纬度
        $start_city = [];
        //结束城市经纬度
        $end_city = [];
        //中间城市经纬度
        $ways_city = [];
        $hasLine = false;
        if(count($allcityLatLngs)>=2 && $da['show_city_map']==1){
            $hasLine  = true;
            $start_city = array_shift($allcityLatLngs);
            $end_city = array_pop($allcityLatLngs);
            $ways_city = $allcityLatLngs;
        }
        $da['keyArr']=$keyArr;
        $da['schedule']=$rc;
        $da['cityMap'] = [
            "hasLine"=>$hasLine,
            "start_city"=>$start_city,
            "end_city"=>$end_city,
            "ways_city"=>$ways_city,
        ];
        $da['city_map_img'] = empty($da['showda_city_map'])?"":$da['thumb_map_img'];
        $da['city_map_name'] = empty($da['show_city_map'])?"":$da['thumb_map_name'];

        if($da['showpricedetail']==1){
            $da['totalPriceData'] = (new TripApi())->getTripTotalPriceDataDetail($da);
        }else{
            $da['totalPriceData'] = ['total'=>0,'detail'=>[]];
        }
        //删除多余字段
        unset($da['total_sale_price'],
            $da['totalExtraPrice_rate'],
            $da['insurancePrice_rate'],
            $da['totalTicketPrice_rate'],
            $da['totalTransPrice_rate'],
            $da['totalDrivePrice_rate'],
            $da['totalHotelPrice_rate'],
            $da['totalAirportPrice_rate'],
            $da['totalAirportPrice'],
            $da['totalTransPrice'],
            $da['totalExtraPrice'],
            $da['totalTicketPrice'],
            $da['totalDrivePrice'],
            $da['totalHotelPrice'],
            $da['insuranceDetail'],
            $da['insurancePrice'],
            $da['total_price'],
            $da['section_json']
        );
        return json_encode(['msg'=>'查询成功','code'=>0,'data'=>$da]);
    }

    public function cdk(){
        $post=request()->request();
        $cdk=  db('tripcdk')
            ->alias('a')
            ->where('a.CDK', $post['cdk'])
            ->join('trip t','t.id=a.trip_id')
            ->field('t.id as trip_id,t.name,a.state,a.isdelete,a.member_id,a.endtime')
            ->find();
        if (!empty($cdk)){
            if ($cdk['state']==2 || $cdk['isdelete']==1||$cdk['endtime']<time()){
                return json_encode(['msg'=>'该CDK已失效或停用','code'=>101]);
            }

            if (!empty($cdk['member_id'])&& $cdk['member_id']!=$post['member_id']) return json_encode(['msg'=>'CDK已绑定他人无法使用','code'=>101]);

            return json_encode(['msg'=>'查询成功','code'=>0,'data'=>$cdk]);
        }else{
            return json_encode(['msg'=>'CDK错误','code'=>101]);
        }
    }

    //获取详情poi详情
    public function poi()
    {
        $post=request()->request();
        $poi = db('poi')->where('id',$post['id'])
            ->field('name,id,groupid,eng_name,introduce,eng_introduce,score,description,ticket,open_time,lat,lng,thumb,groupid,address,total_score,total_comment_num,map_thumb_img,use_time')
            ->find();
        if(empty($poi)){
            return json_encode(['msg'=>'数据为空','code'=>101]);
        }
        if($poi['ticket']!=='免费'){
            $poi['ticket'] = '';
        }

        //增加城市name
        $city = db("city")->where("id",$poi['groupid'])->field("name")->find();
        $poi['city_name'] = $city['name'];

        $images=!empty($poi['thumb'])?explode(',',$poi['thumb']):'';
        if ($images!=''){
            $poi['thumb']= array_filter($images);
        }else{
            $poi['thumb']= '';
        }

        return json_encode(['msg'=>'请求成功','code'=>0,'data'=>$poi]);
    }

    //定制行程确认
    public function confirmTrip()
    {
        $post = request()->post();
        $tripid = $post['id']??0;
        $trip = db('trip')->where(['id'=>$tripid])->find();
        if(empty($tripid) || empty($trip)){
            return json_encode(['code'=>101,'msg'=>'行程有误']);
        }
        //确认行程后锁定trip
        $res = db('trip')->where(['id'=>$tripid])->update(['isConfirm'=>1,'isLocked'=>1]);
        if($res!==false){
            return json_encode(['code'=>200,'msg'=>'行程确认成功']);
        }else{
            return json_encode(['code'=>101,'msg'=>'行程确认失败']);
        }
    }

    //行程用户信息
    public function customMadeTripUserInfo()
    {
        $post = request()->post();
        $tripid = $post['id']??0;
        $tripcustomer = db('tripcustomer tc')
            ->join('trip t','t.id=tc.tripid','left')
            ->where(['tripid'=>$tripid])
            ->field('tc.nickname as username,tc.country_code,tc.phone,tc.wechat,tc.email,tc.age,
            t.name as tripname,t.trip_banner,t.days,t.adult,t.child,t.start_go_time as startDate,t.total_sale_price')
            ->find();
        if(empty($tripid) || empty($tripcustomer)){
            return json_encode(['code'=>101,'msg'=>'行程有误']);
        }
        $tripcustomer['startDate'] = date('Y-m-d',$tripcustomer['startDate']);
        $tripcustomer['trip_banner'] = $tripcustomer['trip_banner']?:"https://kwibon-public-images.oss-cn-beijing.aliyuncs.com/custom/68fa01cd5691eb3282147a796baf1d98jpg";
        return json_encode(['code'=>200,'msg'=>'获取用户信息成功','data'=>$tripcustomer]);
    }

}